package com.camelot.boot.server;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;

public class ResumeExtractor {

    private static final String DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions";
    private static final String API_KEY = "sk-cc3f800cb24b4470871afd2923cdd571";
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    private final OkHttpClient client;

    public ResumeExtractor() {
        this.client  = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
    }

    public Map<String, String> extractResumeInformation(String resumeText) throws IOException {
        // Prepare the prompt for information extraction
        String prompt = "Extract the following information from this resume in JSON format with keys: " +
                "name, email, phone, education (as array), experience (as array), skills (as array). " +
                "Here is the resume text:\n\n" + resumeText;

        // Create the request body for DeepSeek API
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "deepseek-chat");

        JSONArray messages = new JSONArray();
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", prompt);
        messages.put(message);

        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.3);
        requestBody.put("max_tokens", 2000);

        // Make the API request
        RequestBody body = RequestBody.create(requestBody.toString(), JSON);
        Request request = new Request.Builder()
                .url(DEEPSEEK_API_URL)
                .post(body)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            String responseBody = response.body().string();
            JSONObject jsonResponse = new JSONObject(responseBody);

            // Parse the response to extract information
            return parseExtractedInformation(jsonResponse);
        }
    }

    private Map<String, String> parseExtractedInformation(JSONObject jsonResponse) {
        Map<String, String> result = new HashMap<>();

        try {
            JSONArray choices = jsonResponse.getJSONArray("choices");
            if (choices.length() > 0) {
                JSONObject firstChoice = choices.getJSONObject(0);
                JSONObject message = firstChoice.getJSONObject("message");
                String content = message.getString("content");

                // The content should be a JSON string with extracted information
                JSONObject extractedData = new JSONObject(content);

                // Basic information
                result.put("name", extractedData.optString("name", ""));
                result.put("email", extractedData.optString("email", ""));
                result.put("phone", extractedData.optString("phone", ""));

                // Arrays
                result.put("education", extractedData.optJSONArray("education").toString());
                result.put("experience", extractedData.optJSONArray("experience").toString());
                result.put("skills", extractedData.optJSONArray("skills").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static void main(String[] args) {
        try {
            // Read resume text from file (or you can get it from other sources)
            String resumeText = "张三\n电话：13800138000\n邮箱：zhangsan@example.com\n"
                    + "教育背景：\n- 北京大学 计算机科学 本科 2015-2019\n"
                    + "工作经历：\n- 腾讯 软件开发工程师 2020-2023";;

            ResumeExtractor extractor = new ResumeExtractor();
            Map<String, String> extractedInfo = extractor.extractResumeInformation(resumeText);

            // Print extracted information
            System.out.println("Extracted Resume Information:");
            System.out.println("Name: " + extractedInfo.get("name"));
            System.out.println("Email: " + extractedInfo.get("email"));
            System.out.println("Phone: " + extractedInfo.get("phone"));
            System.out.println("Education: " + extractedInfo.get("education"));
            System.out.println("Experience: " + extractedInfo.get("experience"));
            System.out.println("Skills: " + extractedInfo.get("skills"));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}